package com.azh.server.vm;

import com.azh.server.tx.TxManager;

/**
 * @author zhaozhenhang <zhaozhenhang@kuaishou.com>
 * Created on 2022-04-30
 */
public class Visibility {

    public static boolean isVersionSkip(TxManager tx, Tx t, Entry entry) {
        long txMax = entry.getTxMax();
        if (t.level == 0) {
            return false;
        }
        return tx.isCommitted(txMax) && (txMax > t.txId || t.isInSnapshot(txMax));
    }

    public static boolean isVisible(TxManager tx, Tx t, Entry entry) {
        if (t.level == 0) {
            return readCommitted(tx, t, entry);
        }
        return repeatableRead(tx, t, entry);
    }

    /**
     * 判断某个记录是否对事物t可见
     * @param tx
     * @param t
     * @param entry
     * @return
     */
    private static boolean readCommitted(TxManager tx, Tx t, Entry entry) {
        long txId = t.txId;
        long txMin = entry.getTxMin();
        long txMax = entry.getTxMax();
        if (txMin == txId && txMax == 0) {
            return true;
        }
        if (tx.isCommitted(txMin)) {
            if (txMax == 0) {
                return true;
            }
            if (txMax != txId) {
                if (!tx.isCommitted(txMax)) {
                    return true;
                }
            }
        }
        return false;
    }

    private static boolean repeatableRead(TxManager tx, Tx t, Entry entry) {
        long txId = t.txId;
        long txMin = entry.getTxMin();
        long txMax = entry.getTxMax();
        if (txMin == txId && txMax == 0) {
            return true;
        }
        if (tx.isCommitted(txMin) && txMin < txId && !t.isInSnapshot(txMin)) {
            if (txMax == 0) {
                return true;
            }
            if (txMax != txId) {
                if (!tx.isCommitted(txMax) || txMax > txId || t.isInSnapshot(txMax)) {
                    return true;
                }
            }
        }
        return true;
    }
}
